#include "visibilityform.h"
#include "ui_visibilityform.h"
#include "../../protocol/visibilityprotocol.h"
#include "../sys/widgetsysform.h"
#include "../../dataBase/connection.h"
#include "../gloab/globalobserver.h"
#include "../gloab/mymessagebox.h"
#include "QsLog/QsLog.h"


#include <QSerialPortInfo>
#include <QtSql>
//#include <QtConcurrent>

VisibilityForm::VisibilityForm(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::VisibilityForm)
    , m_port(new QSerialPort(this))
{
    ui->setupUi(this);
    formInit();

    connect(this, &VisibilityForm::Sig_DeviceVisibilityProtocol, GlobalObserver::getInstance(), &GlobalObserver::Sig_VisibilityProtocol);
}

VisibilityForm::~VisibilityForm()
{
    delete ui;
}

void VisibilityForm::formInit()
{
    //能见度仪刷新串口按钮
    connect(ui->visSerialPortFleshbtn, &QPushButton::clicked, this, [=](){
        ui->visSerialPortcbx->clear();
        QList<QSerialPortInfo> info_list = QSerialPortInfo::availablePorts();
        QStringList portList;
        QListIterator<QSerialPortInfo> iter(info_list);
        iter.toFront();
        while (iter.hasNext()) {
            QSerialPortInfo info = iter.next();
            portList.append(info.portName());
        }
        if(portList.empty()){
            ui->visSerialPortcbx->addItem("没有串口");
        }else{
            ui->visSerialPortcbx->addItems(portList);
        }
    } );

    //能见度仪的打开串口
    connect(ui->visOpenClosebtn, &QPushButton::clicked, this, [=](){
        if(ui->visOpenClosebtn->text() == "连接"){
            if(ui->visSerialPortcbx->currentText().isEmpty()){

                MyMessageBox msgBox(this, MsgBoxType_Info, "串口未设置");
                msgBox.exec();
                return ;
            }
            QString port = ui->visSerialPortcbx->currentText();
            bool bl = openDevice(port);
            if(!bl){
                qDebug()<<"打开失败";
            }
            else{
                QLOG_INFO()<<CALLPOINTINFO<<"能见度仪连接成功";
                /*启动的时候清空一下之前所有的点*/
                ui->visOpenClosebtn->setText("断开");
            }
        }else{
            closeDevice();
            ui->visOpenClosebtn->setText("连接");
        }
    });
}

bool VisibilityForm::openDevice(QString portName)
{
    m_port->setPortName(portName);
    m_port->setBaudRate(9600);
    m_port->setDataBits(QSerialPort::Data8);
    m_port->setStopBits(QSerialPort::OneStop);
    m_port->setParity(QSerialPort::NoParity);
    m_port->setFlowControl(QSerialPort::NoFlowControl);
    m_port->setReadBufferSize(4096);
    if(m_port->open(QSerialPort::ReadWrite)){
        qDebug()<<"打开成功";
        connect(this->m_port, &QSerialPort::errorOccurred, this, [=](QSerialPort::SerialPortError err){
            qDebug()<<"错误信息 : "<<this->m_port->errorString();
        });


        connect(this->m_port, &QSerialPort::readyRead, this, [=](){
            if(this->m_port->bytesAvailable()  || !m_readBuffer.isEmpty()){
                QByteArray ary = this->m_port->readAll();
                qDebug()<<"rec arr:"<<ary;
                this->m_readBuffer.append(ary);
                int index = this->m_readBuffer.indexOf("VIS");

                // |多余数据|VIS|正确数据|，删除第一次VIS前的所有数据
                if(index > 0 ){
                    this->m_readBuffer.remove(0, index);
                }
                if(index == -1){
                    this->m_readBuffer.remove(0, m_readBuffer.length());
                }
                if(this->m_readBuffer.length() >= VISIBILITY_PROTOCOLALL_LENGTH){
                    int index = this->m_readBuffer.indexOf("VIS");
                    qDebug()<<"index:"<<index<<"  m_readBuffer:"<<this->m_readBuffer;
                    if(index >= 0){
                        QByteArray result = this->m_readBuffer.mid(index, VISIBILITY_PROTOCOLALL_LENGTH);
                        //qDebug()<<"result : "<<result;
                        //在这里直接解析？或者使用信号槽连接
                        resolveProtrocol(result);

                        this->m_readBuffer.remove(index, VISIBILITY_PROTOCOLALL_LENGTH);
                    }
                }
            }
        });
        return true;
    }
    return false;
}

void VisibilityForm::closeDevice()
{
    m_port->close();
}

void VisibilityForm::resolveProtrocol(QByteArray ary)
{

    ary.replace(" ","");
    qDebug()<<"删除空格后的 ary : "<<ary;
    protocol::VisibilityProtocol protocol;
    bool ok;

    QString dataTimeStr = ary.mid(10, 14);
    int year = dataTimeStr.mid(0, 4).toInt(&ok);
    int month = dataTimeStr.mid(4, 2).toInt(&ok);
    int day = dataTimeStr.mid(6, 2).toInt(&ok);
    int hour = dataTimeStr.mid(8, 2).toInt(&ok);
    int minute = dataTimeStr.mid(10, 2).toInt(&ok);
    int second = dataTimeStr.mid(12, 2).toInt(&ok);

    protocol.m_date_time = QDateTime(QDate(year, month, day), QTime(hour, minute, second));


    protocol.m_one_minute_visibility = ary.mid(24, 5).toInt(&ok);
    protocol.m_ten_minute_visibility = ary.mid(29, 5).toInt(&ok);
    protocol.m_TheIntensityOfEmittedEnergy = ary.mid(34, 5).toInt(&ok);
    protocol.m_TheIntensityOfReceivedEnergy = ary.mid(39, 5).toInt(&ok);

    protocol.m_RatedPower = ary.mid(44, 3).toDouble(&ok)/10;
    protocol.m_sendPollution = ary.mid(61, 3).toDouble(&ok)/10;
    protocol.m_receivedPollution = ary.mid(64, 3).toDouble(&ok)/10;
    QString deviceState = ary.mid(67, 8);
    protocol.m_device_code = ary.mid(67, 8);
    protocol.m_deviceState = checkDevState(deviceState);

    //数据解析完成，且封装到protocol中了，发送更新ui的信号，通知能见度仪器数据展示界面进行更新
    emit Sig_DeviceVisibilityProtocol(protocol);



    //解析完成后，组装sql语句
    QUuid uuid = QUuid::createUuid();
    QString strSql = QString("INSERT INTO \"TESTDBA\".\"visibility\"(\"dateTime\",\"oneMinVisibility\",\"tenMinVisibility\",\"emitEnergyIntensity\","
                     "\"receiveEnergyIntensity\",\"ratePower\",\"sendPollution\",\"receivePollution\",\"deviceStateCode\",\"uuid\")"
                             "VALUES('%1','%2','%3','%4','%5','%6','%7','%8','%9','%10');").arg(protocol.m_date_time.toString("yyyy-MM-dd HH:mm:ss"))
                         .arg(protocol.m_one_minute_visibility).arg(QString::number(protocol.m_ten_minute_visibility))
                         .arg(QString::number(protocol.m_TheIntensityOfEmittedEnergy)).arg(QString::number(protocol.m_TheIntensityOfReceivedEnergy))
                         .arg(QString::number(protocol.m_RatedPower)).arg(QString::number(protocol.m_sendPollution)).arg(QString::number(protocol.m_receivedPollution))
                         .arg(protocol.m_device_code).arg(uuid.toString());

   Connection::getInstance()->update(strSql);
    qDebug()<<"更新ui完成";
}

QString VisibilityForm::checkDevState(QString DevStaStr)
{
    QString res = "";
    if(DevStaStr[0] == '1'){
        res.append("设备未校准或校准数据丢失\n");
    }
    if(DevStaStr[1] == '1'){
        res.append("RTC损坏\n");
    }
    if(DevStaStr[2] == '1'){
        res.append("环境温度不良\n");
    }
    if(DevStaStr[3] == '1'){
        res.append("窗口污染\n");
    }
    if(DevStaStr[4] == '1'){
        res.append("电路板温度不良\n");
    }
    if(DevStaStr[5] == '1'){
        res.append("背景光不良\n");
    }
    if(res.size() == 0){
        res.append("无");
    }
    return res;
}
